import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/theme.dart';

import '../../../constants.dart';
import '../../../widget/null_tip.dart';
import 'logic.dart';

class SealPage extends StatelessWidget {
  SealPage({Key? key}) : super(key: key);

  final logic = Get.find<SealLogic>();

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 16.w,
            ),
            onPressed: () {
              Get.back();
            },
          ),
          title:
              logic.isSearching.value ? _buildSearchField() : const Text('用印'),
          bottom: TabBar(
            controller: logic.tabController,
            tabs: logic.tabTitles.map((e) => Tab(text: e)).toList(),
          ),
          actions: [
            if (!logic.isSearching.value) ...[
              IconButton(
                onPressed: () => {logic.onClickSearch()},
                icon: SvgPicture.asset(
                  'assets/icons/ic_search.svg',
                  width: kIconSizeTiny,
                ),
              ),
              IconButton(
                onPressed: () => _showBottomSheet(),
                icon: const Icon(Icons.add),
              ),
            ],
          ],
        ),
        body: logic.isLoading.value
            ? const Center(child: CircularProgressIndicator())
            : RefreshIndicator(
                onRefresh: () async => logic.reload(),
                child: Stack(
                  children: [
                    ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      controller: logic.scrollController,
                      itemBuilder: _renderRow,
                      itemCount: logic.sealList.length + 1,
                    ),
                    if (logic.isSearching.value && !logic.isSearched.value)
                      Container(
                        width: double.maxFinite,
                        height: double.maxFinite,
                        color: const Color(0x55000000),
                      ),
                  ],
                ),
              ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < logic.sealList.length) {
      return Card(
        elevation: 0,
        clipBehavior: Clip.hardEdge,
        margin:
            EdgeInsets.symmetric(horizontal: kSpaceSmall, vertical: kSpaceMini),
        child: Ink(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(kRadiusSmall),
          ),
          child: InkWell(
            onTap: () => logic.toSealDetail(index),
            child: Padding(
              padding: EdgeInsets.all(kSpaceSmall),
              child: Column(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildItem(
                          '时间', logic.sealList[index].createdAtStr ?? ''),
                      SizedBox(height: kSpaceMedium),
                      _buildItem(
                          '申请类型',
                          SealPaperType
                              .values[logic.sealList[index].type!].label),
                      SizedBox(height: kSpaceMedium),
                      _buildItem('状态',
                          sealApplyStatus[logic.sealList[index].status] ?? ''),
                      SizedBox(height: kSpaceMedium),
                      _buildItem('关联案件', logic.sealList[index].caseName ?? ''),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    } else if (logic.sealList.isEmpty) {
      return Column(
        children: [
          SizedBox(height: kSpaceHuge),
          const NullTip(),
        ],
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _buildItem(String title, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontBlack,
          ),
        ),
        SizedBox(width: kSpaceMini),
        Expanded(
          child: Text(
            value,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.right,
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
        ),
      ],
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }

  Widget _buildSearchField() {
    return Container(
      height: 40.w,
      margin: EdgeInsets.only(right: kSpaceMedium),
      child: TextField(
        autofocus: true,
        controller: logic.searchController,
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.search,
        onSubmitted: (value) => logic.onSearch(),
        onTap: () => logic.onClickSearch(),
        decoration: InputDecoration(
          prefixIcon: IconButton(
            icon: SvgPicture.asset(
              'assets/icons/ic_search.svg',
              width: kIconSizeTiny,
              height: kIconSizeTiny,
            ),
            onPressed: () => logic.onSearch(),
          ),
          suffixIcon: IconButton(
            iconSize: kIconSizeTiny,
            icon: const Icon(Icons.close),
            onPressed: () => logic.onCancelSearch(),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(kRadiusMedium),
            borderSide: const BorderSide(color: AppColor.colorBorderGrey),
          ),
          hintText: '案件名关键词',
          hintStyle: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontHint,
          ),
          contentPadding:
              EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
        ),
      ),
    );
  }

  // 底部关联案件弹窗
  void _showBottomSheet() {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: Get.context!,
      isDismissible: false,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
      ),
      builder: (context) {
        return SizedBox(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(
                  left: kSpaceMedium,
                  top: kSpaceTiny,
                  bottom: kSpaceTiny,
                  right: kSpaceTiny,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '请选择申请类型',
                      style: TextStyle(
                        fontSize: kFontSizeMedium,
                        color: AppColor.colorFontBlack,
                      ),
                    ),
                    IconButton(
                      onPressed: () => {Get.back()},
                      icon: SvgPicture.asset(
                        'assets/icons/ic_cancel_black.svg',
                        width: kIconSizeMini,
                      ),
                    ),
                  ],
                ),
              ),
              const Divider(),
              Expanded(
                child: ListView.builder(
                  itemCount: SealPaperType.values.length,
                  itemBuilder: (context, index) {
                    if (SealPaperType.values[index].value == 0 ||
                        SealPaperType.values[index].value == 9) {
                      return Container();
                    }

                    return ListTile(
                      title: Text(
                        SealPaperType.values[index].label,
                        style: TextStyle(
                          fontSize: kFontSizeSmall,
                          color: AppColor.colorFontBlack,
                        ),
                      ),
                      trailing: Obx(
                        () => logic.createPaperType.value ==
                                SealPaperType.values[index]
                            ? SvgPicture.asset(
                                'assets/icons/ic_radio_selected.svg',
                                width: 16.w)
                            : SvgPicture.asset(
                                'assets/icons/ic_radio_unselect.svg',
                                width: 16.w),
                      ),
                      onTap: () => logic
                          .onSelectedCreateType(SealPaperType.values[index]),
                    );
                  },
                ),
              ),
              const Divider(),
              Padding(
                padding: EdgeInsets.all(kSpaceMedium),
                child: Obx(
                  () => FilledButton(
                    onPressed: logic.createPaperType.value == null
                        ? null
                        : () => {Get.back(), logic.toCreateSealApply()},
                    child: Container(
                      alignment: Alignment.center,
                      width: double.infinity,
                      height: 50.w,
                      child: Text(
                        '确认',
                        textAlign: TextAlign.center,
                        style: TextStyle(fontSize: kFontSizeMedium),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
